import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { statisticsApi } from "../api";

export const useStatisticsStore = defineStore("statistics", () => {
  // 状态
  const successRateData = ref([]);
  const timeDistributionData = ref([]);
  const responseTimeData = ref([]);
  const loading = ref(false);

  // 计算属性
  const averageSuccessRate = computed(() => {
    if (successRateData.value.length === 0) return 0;
    const total = successRateData.value.reduce(
      (sum, item) => sum + item.rate,
      0
    );
    return (total / successRateData.value.length).toFixed(2);
  });

  const peakTimeSlot = computed(() => {
    if (timeDistributionData.value.length === 0) return null;
    return timeDistributionData.value.reduce((max, current) =>
      current.count > max.count ? current : max
    );
  });

  const averageResponseTime = computed(() => {
    if (responseTimeData.value.length === 0) return 0;
    const total = responseTimeData.value.reduce(
      (sum, item) => sum + item.time * item.count,
      0
    );
    const count = responseTimeData.value.reduce(
      (sum, item) => sum + item.count,
      0
    );
    return (total / count).toFixed(2);
  });

  // 方法
  const fetchSuccessRate = async (params) => {
    try {
      loading.value = true;
      const response = await statisticsApi.getSuccessRate(params);
      successRateData.value = response.data;
    } catch (error) {
      console.error("获取成功率统计失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  const fetchTimeDistribution = async (params) => {
    try {
      loading.value = true;
      const response = await statisticsApi.getTimeDistribution(params);
      timeDistributionData.value = response.data;
    } catch (error) {
      console.error("获取时段分布统计失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  const fetchResponseTimeDistribution = async (params) => {
    try {
      loading.value = true;
      const response = await statisticsApi.getResponseTimeDistribution(params);
      responseTimeData.value = response.data;
    } catch (error) {
      console.error("获取响应时间分布统计失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  const fetchAllStatistics = async (params) => {
    try {
      loading.value = true;
      await Promise.all([
        fetchSuccessRate(params),
        fetchTimeDistribution(params),
        fetchResponseTimeDistribution(params),
      ]);
    } catch (error) {
      console.error("获取统计数据失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  return {
    // 状态
    successRateData,
    timeDistributionData,
    responseTimeData,
    loading,

    // 计算属性
    averageSuccessRate,
    peakTimeSlot,
    averageResponseTime,

    // 方法
    fetchSuccessRate,
    fetchTimeDistribution,
    fetchResponseTimeDistribution,
    fetchAllStatistics,
  };
});
